import { GetPlaceListForPage,postPlaceAddForUser } from '../../api/home'
import { imageURL } from '../../../utils/request'

Page({
  data: {
    imageURL: '',
    showModal: false,
    days: [],
    diffDays: '',
    places: [],
    page: 1,
    rows: 10,
    keyword: '',
    is_hot: '',
    hasMore: true,
    loading: false,
    selectedDayIndex: 0,  // 选中的DAY索引
    isScrolling: false, // 是否正在滚动
    currentSelectedPlace: null // 当前要添加的景点
  },
  // 滚动开始
  onDayPickerStart() {
    this.setData({
      isScrolling: true
    })
  },

  // 滚动结束
  onDayPickerEnd() {
    this.setData({
      isScrolling: false
    })
  },
  back(){
    wx.navigateBack()
  },
  onLoad(e) {
    const days = Array.from({ length: e.diffDays }, (_, i) => `DAY ${i + 1}`);
    this.getData(true); // 初始化加载
    this.setData({
      imageURL,
      days,
      diffDays: e.diffDays
    })
  },
  onShow() {
    const payload = wx.getStorageSync('payload') || { list_item: [] };
    const selectedIds = payload.list_item.flatMap(d => d.child.map(c => c.place_id));
  
    if (this.data.places.length > 0) {
      const updatedPlaces = this.data.places.map(p => ({
        ...p,
        selected: selectedIds.includes(p.place_id)
      }));
      this.setData({ places: updatedPlaces });
    }
  },
  
  // 搜索输入事件
  onInput(e) {
    this.setData({ keyword: e.detail.value });
    if (e.detail.value == '') {
      this.setData({ page: 1, places: [], hasMore: true });
      this.getData(true);
    }
  },
   chooseLocation(e) {
  
    wx.chooseLocation({
      success:  (res) => {
        console.log("选中的地点：", res);
        if(res.name){
          this.addJd(res)
        }else{
          wx.showToast({
            title: '請選擇需要添加的景點',
            icon:'none'
          })

        }
        
        
      },
      fail: (err) => {
        console.log("用户未选择地点", err);
      }
    });
  },
  async addJd(res){
    const info = await postPlaceAddForUser({
      "name": res.name,
      "address": res.address,
      "longitude": res.longitude,
      "latitude": res.latitude
    })
      this.setData({ page: 1, places: [], hasMore: true });
       await this.getData(true);
        wx.showToast({
          title: '添加成功',
        })
  },
  // 搜索确认事件
  onSearch() {
    this.setData({ page: 1, places: [], hasMore: true });
    this.getData(true);
  },

  // 获取数据
  async getData(reset = false) {
  if (this.data.loading || !this.data.hasMore) return;

  this.setData({ loading: true });

  const res = await GetPlaceListForPage({
    page: this.data.page,
    rows: this.data.rows,
    keyword: this.data.keyword,
    is_hot: this.data.is_hot
  });

  // 本地已选的 place_id 列表
  const payload = wx.getStorageSync('payload') || { list_item: [] };
  const selectedIds = payload.list_item.flatMap(d => d.child.map(c => c.place_id));

  const newList = (res.data.list || []).map(item => ({
    ...item,
    selected: selectedIds.includes(item.place_id) // ✅ 判定是否已选
  }));

  this.setData({
    places: reset ? newList : [...this.data.places, ...newList],
    page: this.data.page + 1,
    hasMore: newList.length === this.data.rows,
    loading: false
  });
  },


  // 上拉触底
  onReachBottom() {
    this.getData();
  },

  // 选择切换
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    let showModal = false;
    let currentSelectedPlace = null;

    const places = this.data.places.map(p => {
      if (p.place_id === id) {
        const newSelected = !p.selected;
        if (!p.selected && newSelected) {
          // 从 false 变 true -> 弹窗选择 DAY
          showModal = true;
          currentSelectedPlace = p;
        } else if (p.selected && !newSelected) {
          // 从 true 变 false -> 删除
          this.removePlaceFromPayload(p.place_id);
        }
        return { ...p, selected: newSelected };
      }
      return p;
    });

    this.setData({ 
      places,
      showModal,
      currentSelectedPlace
    });
  },

  // picker 改变 DAY
  onDayPickerChange(e) {
    const index = e.detail.value[0];
    this.setData({ selectedDayIndex: index });
  },

  // 确认选择 -> 更新本地 payload
  confirmSelect() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }
    const place = this.data.currentSelectedPlace
    const day_num = this.data.selectedDayIndex + 1
    const selectedDayIndex = this.data.selectedDayIndex
    if (!place) {
      wx.showToast({ title: '未選擇地點', icon: 'none' })
      return
    }

    let payload = wx.getStorageSync('payload') || {
      itinerary_id: '',
      itinerary_catalog_id: '',
      name: '',
      transportation: 1,
      start_time: '',
      end_time: '',
      img_url_cover: '',
      list_item: []
    }

    // 初始化封面
    if (!payload.img_url_cover) {
      payload.img_url_cover = place.img_url_cover || ''
    }

    // 查找当天
    let dayItem = payload.list_item.find(d => d.day_num === day_num)
    if (!dayItem) {
      dayItem = { theme: '', day_num, child: [] }
      payload.list_item.push(dayItem)
    }

    // 检查是否已存在
    const exists = dayItem.child.some(c => c.place_id === place.place_id)
    if (!exists) {
      dayItem.child.push({
        place_id: place.place_id,
        title: place.name,
        introduction: place.introduction,
        count_favorite:place.count_favorite,
        selected:true,
        type: 11,
        start_time: '',
        end_time: '',
        img_url_cover: place.img_url_cover || ''
      })
    }

    // 保证 list_item 按 day_num 排序
    payload.list_item.sort((a, b) => a.day_num - b.day_num)

    // 存储
    wx.setStorageSync('payload', payload)

    this.setData({
      showModal: false,
      currentSelectedPlace: null,
      selectedDayIndex:selectedDayIndex,
    })

    wx.showToast({ title: '已添加', icon: 'success' })
  },

  // 删除景点
  removePlaceFromPayload(place_id) {
    let payload = wx.getStorageSync('payload') || {}
    if (!payload.list_item) return

    payload.list_item.forEach(dayItem => {
      dayItem.child = dayItem.child.filter(c => c.place_id !== place_id)
    })

    // 删除空的 day
    payload.list_item = payload.list_item.filter(d => d.child.length > 0)

    wx.setStorageSync('payload', payload)
  },

  // 查看收藏
  goToFavorites() {
    wx.navigateTo({ 
      url: `/pages/Itinerary/addItineraryCollect/addItineraryCollect?diffDays=${this.data.diffDays}`
    });
  }
})
